// NetTetrisDlg.cpp : implementation file
//

#include "stdafx.h"
#include "NetTetris.h"
#include "NetTetrisDlg.h"
#include "LocalPane.h"
#include "NextElementPane.h"
#include "Element.h"
#include "Utility.h"

#include "RemotePane.h"

#include "ClientManager.h"
#include "LocalDisplayer.h"
#include "RemoteDisplayer.h"
#include "GameConfiger.h"
#include "Chatter.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CNetTetrisDlg dialog




CNetTetrisDlg::CNetTetrisDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CNetTetrisDlg::IDD, pParent)
    , m_pSquarePane(NULL)
    , m_pNextElementPane(NULL)
    , m_pCurrentElement(NULL)
    , m_bSingleMode(true)
    , m_bStart(false)
    , m_bPause(false)
    , m_bGameOver(false)
    , m_bElementStop(false)
    , m_bShowRemotePane(false)
    , m_iPlayMode(0)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CNetTetrisDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    DDX_Radio(pDX, IDC_RADIO_SINGLE, m_iPlayMode);
}

void CNetTetrisDlg::Init()
{
    // Game level
    CComboBox *pGameLevelComboBox = (CComboBox*)GetDlgItem(IDC_COMBO_GAME_LEVEL);
    pGameLevelComboBox->AddString(TEXT("1"));
    pGameLevelComboBox->AddString(TEXT("2"));
    pGameLevelComboBox->AddString(TEXT("3"));
    pGameLevelComboBox->AddString(TEXT("4"));
    pGameLevelComboBox->AddString(TEXT("5"));
    pGameLevelComboBox->AddString(TEXT("6"));
    pGameLevelComboBox->AddString(TEXT("7"));
    pGameLevelComboBox->AddString(TEXT("8"));
    pGameLevelComboBox->AddString(TEXT("9"));
    pGameLevelComboBox->SetCurSel(0);

    // Spin mode
    CComboBox *pSpinModeComboBox = (CComboBox*)GetDlgItem(IDC_COMBO_SPIN_MODE);
    pSpinModeComboBox->AddString(TEXT("clock wise"));
    pSpinModeComboBox->AddString(TEXT("counter clock wise"));
    pSpinModeComboBox->SetCurSel(0);

    // Play mode
    //((CButton*)GetDlgItem(IDC_RADIO_SINGLE))->SetCheck(1);
    //((CButton*)GetDlgItem(IDC_RADIO_ONLINE))->SetCheck(0);


    // Score 
    SetDlgItemInt(IDC_SCORE, 0);
    
    // Game level
    char buff[8];
    pGameLevelComboBox->GetWindowTextW((LPTSTR)buff, 8);
    SetDlgItemText(IDC_LEVEL, (LPCTSTR)buff);

    // Dialog rect
    this->GetWindowRect(&m_rectDlg);

}

BEGIN_MESSAGE_MAP(CNetTetrisDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
    ON_WM_TIMER()
	//}}AFX_MSG_MAP
    ON_BN_CLICKED(ID_BUTTON_START, &CNetTetrisDlg::OnBnClickedButtonStart)
    ON_BN_CLICKED(ID_BUTTON_QUIT, &CNetTetrisDlg::OnBnClickedButtonQuit)
    ON_WM_KEYDOWN()
    ON_BN_CLICKED(IDC_SHOW_REMOTE, &CNetTetrisDlg::OnBnClickedShowRemote)
    ON_BN_CLICKED(IDC_RADIO_ONLINE, &CNetTetrisDlg::OnBnClickedRadioOnline)
    ON_BN_CLICKED(ID_BUTTON_LOGON, &CNetTetrisDlg::OnBnClickedButtonLogon)
    ON_BN_CLICKED(IDC_INVITE_MEMBER, &CNetTetrisDlg::OnBnClickedInviteMember)
END_MESSAGE_MAP()


// CNetTetrisDlg message handlers

BOOL CNetTetrisDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here
    //m_pSquarePane = new CLocalPane(GetDlgItem(IDC_LOCAL_SHOW_PANE), ROW_NUM, COL_NUM);
    //ASSERT(NULL != m_pSquarePane);

    //m_pNextElementPane = new CNextElementPane(m_pSquarePane, GetDlgItem(IDC_NEXT_ELEMENT));
    //ASSERT(NULL != m_pNextElementPane);

    //m_pCurrentElement = m_pSquarePane->UpdateElement();

    Init();

    m_pClientManager = new CClientManager();
    ASSERT(NULL != m_pClientManager);

    m_pLocalDisplayer = new CLocalDisplayer();
    ASSERT(NULL != m_pLocalDisplayer);

    m_pRemoteDisplayer = new CRemoteDisplayer(this, m_pClientManager);
    ASSERT(NULL != m_pRemoteDisplayer);

    m_pGameConfiger = new CGameConfiger();
    ASSERT(NULL != m_pGameConfiger);

    m_pChatter = new CChatter(m_pClientManager);
    ASSERT(NULL != m_pChatter);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CNetTetrisDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CNetTetrisDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
        if (NULL != m_pSquarePane)
        {
            m_pSquarePane->Draw();
        }

        if (NULL != m_pNextElementPane)
        {
            m_pNextElementPane->DrawNextElement(false);
        }

		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CNetTetrisDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CNetTetrisDlg::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: Add your message handler code here and/or call default

	if (!m_bStart || m_bPause || m_bGameOver)
		return;

	switch(nIDEvent)
	{
		case DOWN_TIMER:
		{
			//if (!m_pCurrentElement->GoDown())
			//{
			//	m_pSquarePane->MergeElement();
   //             
   //             SetDlgItemInt(IDC_SCORE, m_pSquarePane->GetScore());

   //             m_pCurrentElement = NULL;

			//	m_bElementStop = true;
			//}

			//if (m_bElementStop)
			//{
			//	m_pCurrentElement = m_pSquarePane->UpdateElement();

   //             ASSERT(NULL != m_pCurrentElement);

   //             if (!m_pSquarePane->ValidateElement(m_pCurrentElement))
   //             {
   //                 m_bGameOver = true;
   //                 
   //                 ((CButton*)GetDlgItem(ID_BUTTON_START))->SetWindowTextW(TEXT("Restart"));

   //                 break;
   //             }
   //             
   //             m_pNextElementPane->DrawNextElement();

			//	m_bElementStop = false;
			//}
			//
   //         // Draw
   //         m_pSquarePane->Draw();
			
            if (!m_pLocalDisplayer->Update())
            {
                ((CButton*)GetDlgItem(ID_BUTTON_START))->SetWindowTextW(TEXT("Restart"));
                m_bGameOver = true;
            }

			break;
		}
		default:
			break;
	}

	CDialog::OnTimer(nIDEvent);
}
void CNetTetrisDlg::OnBnClickedButtonStart()
{
    // TODO: Add your control notification handler code here
    CRect rectDlg;
    ::GetWindowRect(this->m_hWnd, rectDlg);
    if (!m_bStart)
    {
        // Game level

       // char szGameLevel[8];
       // ((CComboBox*)GetDlgItem(IDC_COMBO_GAME_LEVEL))->GetWindowTextW((LPTSTR)szGameLevel, 8);
       // SetDlgItemText(IDC_LOCAL_GAME_LEVEL, (LPCTSTR)szGameLevel); 

       // // Start Timer
       // UINT nLevel = atoi(szGameLevel);
       // SetTimer(DOWN_TIMER, 1000/nLevel, NULL);
       //
       //((CComboBox*)GetDlgItem(IDC_COMBO_GAME_LEVEL))->EnableWindow(false);

       // 
       // ((CButton*)GetDlgItem(IDC_RADIO_SINGLE))->EnableWindow(false);
       // ((CButton*)GetDlgItem(IDC_RADIO_ONLINE))->EnableWindow(false);
       // 
       // // Change start button text
       // ((CButton*)GetDlgItem(ID_BUTTON_START))->SetWindowTextW(TEXT("Pause"));

        m_pGameConfiger->DisableAll();

        m_bStart = true;
    }
    else
    {
        if (m_bGameOver)
        {
            m_bGameOver = false;
            m_bPause = false;
            m_bStart = false;
            m_bElementStop = false;

            // Start button
            ((CButton*)GetDlgItem(ID_BUTTON_START))->SetWindowTextW(TEXT("Start"));

            m_pGameConfiger->EnableAll();

            //((CComboBox*)GetDlgItem(IDC_COMBO_SPIN_MODE))->EnableWindow(true);
            //((CComboBox*)GetDlgItem(IDC_COMBO_GAME_LEVEL))->EnableWindow(true);
            //((CButton*)GetDlgItem(IDC_RADIO_SINGLE))->EnableWindow(true);
            //((CButton*)GetDlgItem(IDC_RADIO_ONLINE))->EnableWindow(true);

            m_pLocalDisplayer->Reset();
            m_pLocalDisplayer->Update();

            //m_pSquarePane->Restart();
            //m_pNextElementPane->Restart();

            //m_pCurrentElement = m_pSquarePane->UpdateElement();

            //Invalidate();

            //m_pSquarePane->Draw();
            //m_pNextElementPane->DrawNextElement();

        }
        else
        {
            if (!m_bPause)
            {
                ((CButton*)GetDlgItem(ID_BUTTON_START))->SetWindowTextW(TEXT("Pause"));
                m_bPause = true;
            }
            else
            {
                ((CButton*)GetDlgItem(ID_BUTTON_START))->SetWindowTextW(TEXT("Start"));
                m_bPause = false;
            }
        }
    }
}

void CNetTetrisDlg::OnBnClickedButtonQuit()
{
    // TODO: Add your control notification handler code here
    ::PostQuitMessage(0);
}

BOOL CNetTetrisDlg::PreTranslateMessage(MSG* pMsg)
{
	if (pMsg->wParam == VK_DOWN || 
        pMsg->wParam == VK_UP ||
		pMsg->wParam == VK_LEFT || 
        pMsg->wParam == VK_RIGHT)
	{
		SendMessage(pMsg->message, pMsg->wParam, pMsg->lParam);
	}

	return CDialog::PreTranslateMessage(pMsg);
}

void CNetTetrisDlg::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    // TODO: Add your message handler code here and/or call default
    if (!m_bStart || m_bGameOver || !m_pCurrentElement)
		return;

    switch (nChar)
	{
		case VK_LEFT:
		{
            m_pLocalDisplayer->MoveElement(EM_LEFT);

			//if (m_pCurrentElement->GoLeft())
   //         {
			//    m_pSquarePane->Draw();
   //         }

			break;
		}
		case VK_RIGHT:
		{
			//if (m_pCurrentElement->GoRight())
   //         {
			//    m_pSquarePane->Draw();
   //         }
            m_pLocalDisplayer->MoveElement(EM_RIGHT);

			break;
		}
		case VK_UP:
		{
            m_pLocalDisplayer->MoveElement(EM_SPIN);

			//if (m_pCurrentElement->Spin())
   //         {
			//    m_pSquarePane->Draw();
   //         }

			break;
		}
		case VK_DOWN:
		{
            m_pLocalDisplayer->MoveElement(EM_DOWN);

			//if (m_pCurrentElement->GoDown())
   //         {
			//    m_pSquarePane->Draw();
   //         }

			break;
		}
		default:
			break;
	}

    CDialog::OnKeyDown(nChar, nRepCnt, nFlags);
}

void CNetTetrisDlg::OnBnClickedShowRemote()
{
    // TODO: Add your control notification handler code here

    if (!m_bShowRemotePane)
    {
        GetDlgItem(IDC_SHOW_REMOTE)->SetWindowTextW(_T("<<"));
        m_bShowRemotePane = true;

        m_pRemoteDisplayer->Show(true);

        //CRect rectPaneFrame;
        //this->GetDlgItem(IDC_LOCAL_PANE_FRAME)->GetWindowRect(rectPaneFrame);

        //CRect newRect;
        //newRect.SetRect(m_rectDlg.left, m_rectDlg.top, m_rectDlg.right + rectPaneFrame.Width(), m_rectDlg.bottom);

        //MoveWindow(newRect);
    }
    else
    {
        GetDlgItem(IDC_SHOW_REMOTE)->SetWindowTextW(_T(">>"));
        m_bShowRemotePane  = false;

 /*       MoveWindow(m_rectDlg);*/
        m_pRemoteDisplayer->Show(false);
    }
}

void CNetTetrisDlg::OnBnClickedRadioOnline()
{
    // TODO: Add your control notification handler code here
    CRect rectDlg;
    ::GetWindowRect(this->m_hWnd, rectDlg);
    MessageBox(_T("On line mode"));
}

void CNetTetrisDlg::OnBnClickedButtonLogon()
{
    // TODO: Add your control notification handler code here
    MessageBox(_T("Log on"));
}

void CNetTetrisDlg::OnBnClickedInviteMember()
{
    // TODO: Add your control notification handler code here

    GetDlgItem(IDC_SHOW_REMOTE)->SetWindowTextW(_T("<<"));
    m_bShowRemotePane = true;

    //m_pRemoteDisplayer->Show();

    m_pRemoteDisplayer->InviteMember();
}
